package net.yxsoft.service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.kit.Helper;
import net.yxsoft.model.SSynDetails;
import net.yxsoft.model.SSynonyms;
import net.yxsoft.service.common.BaseService;
import rapid.core.Authuser;
import rapid.core.TResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 彭涛涛 2019-6-5
 */
public class SynonymService extends BaseService {
  public static final SynonymService INSTANCE = new SynonymService();
  private SSynonyms synDao = new SSynonyms().dao();
  private SSynDetails synDetailDao = new SSynDetails().dao();

  /**
   * 新增编辑主表(同意词)信息
   */
  public TResult saveObjects(SSynonyms syn, Authuser loginUser) {
    if(StrKit.notNull(loginUser)) {
      Date date = new Date(System.currentTimeMillis());
      String Logs = "";
      if(StrKit.isBlank(syn.getConflictId())) {
        Record isExist = Db.findFirst("select a.conflict_id from s_synonyms a \n" +
                                                " left join s_syn_details b \n" +
                                                " on a.conflict_id = b.row_id \n" +
                                                " where a.attrib_01=? or b.attrib_01=? ", syn.getAttrib01(), syn.getAttrib01());
        if(null == isExist) {
          syn.setConflictId(Helper.bulidUUID());
          syn.setRowId(syn.getConflictId());
          syn.setCreated(date);
          syn.setCreatedBy(loginUser.getName());
          if(syn.save() != true) {
            return TResult.fail("保存失败！");
          }
          Logs = "主键:" + syn.getConflictId() + "名称：" + syn.getAttrib01();
          log(loginUser.getId(), loginUser.getName(), "基础信息管理/同意词管理-主表", "新增", loginUser.getIp(), Logs);
        } else {
          return TResult.fail("您输入的同意词名称已存在！");
        }
      } else {
        SSynonyms synOject = synDao.findById(syn.getConflictId());
        if(null != synOject) {
          Record isExist = Db.findFirst("select a.conflict_id from s_synonyms a \n" +
                                           " left join s_syn_details b \n" +
                                           " on a.conflict_id = b.row_id \n" +
                                           " where (a.attrib_01=? or b.attrib_01=?) and a.conflict_id<>? ", syn.getAttrib01(), syn.getAttrib01(),syn.getConflictId());
          Logs = "主键:" + synOject.getConflictId() + "修改前名称：" + synOject .getAttrib01() + ";修改后名称：" + syn.getAttrib01();
          if(null == isExist) {
            synOject.setLastUpd(date);
            synOject.setLastUpdBy(loginUser.getName());
            synOject.setAttrib01(syn.getAttrib01());
            if(synOject.update() != true) {
              return TResult.fail("编辑失败！");
            }
            log(loginUser.getId(), loginUser.getName(), "基础信息管理/同意词管理-主表", "编辑", loginUser.getIp(), Logs);
            List<String> _sqlList = new ArrayList<>();
            _sqlList.add(String.format(" update s_syn_details set attrib_02='%s' where row_id='%s' ",syn.getAttrib01(),syn.getConflictId()));
            Db.batch(_sqlList, 10000);
          }else{
            return TResult.fail("您输入的同意词名称已存在！");
          }


        } else {
          return TResult.fail("您编辑的数据不存在或已被删除！");
        }
      }
    } else {
      return TResult.fail("未获得用户信息,请重新登录！");
    }
    return success();
  }

  /**
   * 删除主表(同意词)信息
   */
  public TResult deleteObjects(String[] ids, Authuser loginUser) {

    String Logs = "";
    if(ids.length > 0) {
      List<String> _sqlList = new ArrayList<String>();
      for(int i = 0; i < ids.length; i++) {
        _sqlList.add(String.format("delete from s_synonyms where conflict_id='%s' ", ids[i]));
        _sqlList.add(String.format("delete from s_syn_details where row_id='%s' ", ids[i]));
      }
      Db.batch(_sqlList, 10000);
    } else {
      return fail("您删除的数据不存在或已经被删除！");
    }
    Logs = "主键:" + ids.toString();
    log(loginUser.getId(), loginUser.getName(), "基础信息管理/同意词管理-主表", "删除", loginUser.getIp(), Logs);
    return success();
  }

  /**
   * 新增编辑子表(同意词集合)信息
   */
  public TResult saveDetailObjects(SSynDetails details, Authuser loginUser) {
    if(StrKit.notNull(loginUser)) {
      Date date = new Date(System.currentTimeMillis());
      String Logs = "";
      if(StrKit.isBlank(details.getConflictId())) {
        Record isExist = Db.findFirst("select a.conflict_id from s_synonyms a \n" +
                                        " left join s_syn_details b \n" +
                                        " on a.conflict_id = b.row_id \n" +
                                        " where a.attrib_01=? or b.attrib_01=? ", details.getAttrib01(), details.getAttrib01());
        if(null == isExist) {
          Record record = Db.findFirst("select *from s_synonyms where conflict_id =?",details.getRowId());
          details.setAttrib02(record.getStr("attrib_01"));
          details.setConflictId(Helper.bulidUUID());
          details.setCreated(date);
          details.setCreatedBy(loginUser.getName());
          if(details.save() != true) {
            return TResult.fail("保存失败！");
          }
          Logs = "主键:" + details.getConflictId() + "名称：" + details.getAttrib01();
          log(loginUser.getId(), loginUser.getName(), "基础信息管理/同意词管理-子表", "新增", loginUser.getIp(), Logs);
        } else {
          return TResult.fail("您输入的同意词名称已存在！");
        }
      } else {
        SSynDetails synDetailOject = synDetailDao.findById(details.getConflictId());
        if(null != synDetailOject) {
          Record isExist = Db.findFirst("select a.conflict_id from s_synonyms a \n" +
                                          " left join s_syn_details b \n" +
                                          " on a.conflict_id = b.row_id  and b.conflict_id<>? \n" +
                                          " where (a.attrib_01=? or b.attrib_01=?)",details.getConflictId(), details.getAttrib01(), details.getAttrib01());
          if(null == isExist) {
            Logs = "主键:" + synDetailOject.getConflictId()+ "修改前名称：" + synDetailOject .getAttrib01() + ";修改后名称：" + details.getAttrib01();
            synDetailOject.setLastUpd(date);
            synDetailOject.setLastUpdBy(loginUser.getName());
            synDetailOject.setAttrib01(details.getAttrib01());
            if(synDetailOject.update() != true) {
              return TResult.fail("编辑失败！");
            }
            log(loginUser.getId(), loginUser.getName(), "基础信息管理/同意词管理-子表", "编辑", loginUser.getIp(), Logs);
          }else{
            return TResult.fail("您输入的同意词名称已存在！");
          }


        } else {
          return TResult.fail("您编辑的数据不存在或已被删除！");
        }
      }
    } else {
      return TResult.fail("未获得用户信息,请重新登录！");
    }
    return success();
  }

  /**
   * 删除子表(同意词集合)信息
   */
  public TResult deleteDetailObjects(String[] ids, Authuser loginUser) {
    String Logs = "";
    if(ids.length > 0) {
      List<String> _sqlList = new ArrayList<String>();
      for(int i = 0; i < ids.length; i++) {
        _sqlList.add(String.format("delete from s_syn_details where conflict_id='%s' ", ids[i]));
      }
      Db.batch(_sqlList, 10000);
    } else {
      return fail("您删除的数据不存在或已经被删除！");
    }
    Logs = "主键:" + ids.toString();
    log(loginUser.getId(), loginUser.getName(), "基础信息管理/同意词管理-子表", "删除", loginUser.getIp(), Logs);
    return success();
  }


}
